<!-- 用户编辑弹窗 -->
<template>
  <ele-modal width="680px"
             :visible="visible"
             :append-to-body="true"
             :close-on-click-modal="true"
             :title="isUpdate ? '修改帮助中心' : '添加帮助中心'"
             @update:visible="updateVisible">
    <el-form ref="form"
             :model="form"
             :rules="rules"
             label-width="82px">
      <el-row :gutter="15">
        <el-col :span="12">
          <el-form-item label="主标题:"
                        prop="heading">
            <el-input style="width: 230px;"
                      clearable
                      :maxlength="20"
                      v-model="form.heading"
                      placeholder="请输入主标题" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分类标签:"
                        prop="sortLabel">
            <div class="flex-between">
              <el-select clearable
                         class="ele-block"
                         v-model="form.sortLabel"
                         @visible-change="(event) => sortLabelListFn(event)"
                         placeholder="请选择分类标签">
                <el-option v-for="(item, index) in dynamicTagsHelp"
                           :key="index"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <!-- <el-input style="width: 230px;"
                        clearable
                        :maxlength="1"
                        v-model.number="form.sortLabel"
                        placeholder="请输入分类标签" /> -->
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12"
                style="padding-top: 20px;padding-bottom: 20px">
          <!--根据排序值，进行页面排序 -->
          <el-form-item label="排序值:"
                        prop="sortValues">
            <div class="delInput">
              <el-input oninput="value=value.replace(/[^0-9]/g,'')"
                        type="number"
                        style="width: 230px;"
                        clearable
                        :maxlength="20"
                        v-model.number="form.sortValues"
                        placeholder="请输入排序值" />
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12"
                style="padding: 20px 15.5px">
          <el-form-item label="视频地址"
                        prop="icon">
            <!-- <div class="flex-between upload-class">
              
              <div class="font-overflow">建议上传40px * 40px尺寸</div>
            </div> -->
            <!--:before-upload="beforeAvatarUpload"-->
            <!-- <ele-image-upload :item-style="{ width: '40px', height: '40px' }"
                              accept=".jpg,.jpeg,.png"
                              :limit="1"
                              :multiple="false"
                              v-model="bgImgs"
                              :auto-upload="false"
                              :before-remove="onBeforeRemove" /> -->
            <el-input clearable
                      v-model.number="form.icon"
                      placeholder="请上传视频地址" />
          </el-form-item>
        </el-col>
        <el-col style="padding: 0 10px">
          <!--v-if防止tinymce在弹框创建前创建-->
          <tinymce-editor v-if="visible"
                          ref="editor"
                          v-model="form.content"
                          :init="option"
                          :disabled="false" />
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="updateVisible(false)">取消</el-button>
      <el-button type="primary"
                 :loading="loading"
                 @click="save">
        保存
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
import { getHostSysConfigInfo } from '@/api/system/centerCoverImage'
import EleImageUpload from 'ele-admin/es/ele-image-upload';
import { saveShelp } from "@/api/system/helpCenter"
import TinymceEditor from '@/components/TinymceEditor/index.vue';
import { mainOssSignature } from "@/api/creatCenter/material";
import { getToken } from "@/utils/token-util";
import axios from "axios";

export default {
  components: { TinymceEditor, EleImageUpload },
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  data () {
    const defaultForm = {
      icon: '',
    };
    return {
      bgImgs: [],
      option: {
        height: 350,
        // 自定义文件上传(这里使用把选择的文件转成 blob 演示)
        file_picker_callback: (callback, _value, meta) => {
          const input = document.createElement('input');
          input.setAttribute('type', 'file');
          // 设定文件可选类型
          if (meta.filetype === 'image') {
            input.setAttribute('accept', 'image/*');
          } else if (meta.filetype === 'media') {
            input.setAttribute('accept', 'video/*');
          }
          input.onchange = () => {
            const file = input.files?.[0];
            if (!file) {
              return;
            }
            if (meta.filetype === 'media') {
              if (!file.type.startsWith('video/')) {
                this.$refs.editor.alert({ content: '只能选择视频文件' });
                return;
              }
            }
            if (file.size / 1024 / 1024 > 20) {
              this.$refs.editor.alert({ content: '大小不能超过 20MB' });
              return;
            }
            const reader = new FileReader();
            reader.onload = (e) => {
              if (e.target?.result != null) {
                const blob = new Blob([e.target.result], { type: file.type });
                callback(URL.createObjectURL(blob));
              }
            };
            reader.readAsArrayBuffer(file);
          };
          input.click();
        }
      },
      defaultForm,
      // 表单数据
      form: {
        ...defaultForm
      },
      dynamicTagsHelp: [],

      // 表单验证规则
      rules: {
        sortValues: [
          {
            required: true,
            message: '请输入排序值',
            trigger: 'blur'
          }
        ],
        heading: [
          {
            required: true,
            message: '请输入主标题',
            trigger: 'blur'
          }
        ],
        sortLabel: [
          {
            required: true,
            message: '请输入分类标签',
            trigger: 'blur'
          }
        ],
        icon: [
          {
            required: true,
            message: '请上传视频地址',
            trigger: 'blur'
          }
        ]
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false
    };
  },
  computed: {
    // 是否开启响应式布局
    styleResponsive () {
      return this.$store.state.theme.styleResponsive;
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      const res = await getHostSysConfigInfo()

      const msg = res.data
      console.log(msg);
      if (msg.id) {
        //   是修改


        let helpList = []
        if (msg.helpSortLabel.length) {
          if (msg.helpSortLabel.includes(',')) {
            console.log('字符串中包含逗号');
            // 包含的进行slice(',') 分割
            helpList = msg.helpSortLabel.split(',').map((item) => item.trim());
          } else {
            console.log('字符串中不包含逗号');
            helpList = msg.helpSortLabel.split();
          }
          this.dynamicTagsHelp = helpList.map((item) => {
            return {
              label: item,
              value: item
            }
          })
        }


      } else {
        // 修改
        this.dynamicTagsHelp = []
      }

    },
    /* 保存编辑 */
    save () {
      console.log('this.form,this.data', this.form, this.data, this.form == this.data, JSON.stringify(this.form) === JSON.stringify(this.data))
      if (JSON.stringify(this.form) === JSON.stringify(this.data)) {
        this.$message.error('帮助中心未修改！')
        return
      }
      if (this.bgImgs.length > 0 && this.bgImgs[0].file) {
        this.form.icon = 1
      }
      this.$refs.form.validate((valid) => {
        console.log("valid=======", valid, 'this.form', this.form)
        if (valid) {
          if (!this.form.content) {
            this.$message.error("请输入帮助内容！")
            return
          }
          this.loading = true;
          // form.id存在，代表修改，并且icon !=1,则跳过 “上传图片到阿里云” 接口
          this.saveShelp()
          //   if (this.form.id) {
          //     this.saveShelp()
          //   }
          //   else {
          //     this.uploadBj()  // 上传背景图
          //   }
        } else {
          return false;
        }
      });
    },

    async uploadBj () {
      // 获取文件上传签名数据
      this.dataInfo = await mainOssSignature()
      for (let i = 0; i < this.bgImgs.length; i++) {
        let file = this.bgImgs[i].file
        let filename = file.name;
        let markIndex = (filename).lastIndexOf('.');
        let suffix = filename.substring(markIndex)    // 图片后缀(例.jpg)
        let date = new Date().getTime();    // 当前时间戳
        // 构建请求参数
        let param = new FormData()
        param.append("key", this.dataInfo.dir + date + suffix)
        param.append("policy", this.dataInfo.policy)
        param.append("OSSAccessKeyId", this.dataInfo.accessId)
        param.append("success_action_status", '200')
        // param.append("callback",  this.dataInfo.callback)     //回调（not)
        param.append("signature", this.dataInfo.signature)
        param.append("file", file, file.name)
        param.append('success_action_status', '200')
        let config = {
          headers: {
            'Access-Control-Allow-Origin': '*',
            'x-oss-callback-Authorization': getToken()
          }
        }
        axios.post(this.dataInfo.host, param, config).then(res => {
          if (res.status == 200) {
            console.log('this.dataInfo.host', this.dataInfo.host + '/' + date + suffix)
            let url = this.dataInfo.host + '/' + date + suffix;
            this.form.icon = url;
            console.log(" this.form", this.form)
            this.saveShelp()
          }
          else {
            this.loading = false
            this.$message.error('上传失败');
          }

        }).catch(err => {
          console.log(err)
        })
      }
    },
    // 保存帮助中心
    saveShelp () {
      console.log("ssave========", this.form)
      saveShelp(this.form)
        .then((data) => {
          console.log("成功data", data)
          this.loading = false;
          this.$message.success(data.msg);
          this.updateVisible(false);
          this.$emit('done');
        })
        .catch((e) => {
          this.loading = false;
          this.$message.error(e);
        });
    },

    // 暂未使用_—— 强制图片上传尺寸
    beforeAvatarUpload (file) {
      let isSize = true;
      const reader = new FileReader();
      console.log("reader", reader)
      reader.readAsDataURL(file);
      reader.onload = (theFile) => {
        const image = new Image();
        console.log("theFile", theFile)
        image.src = theFile.target.result;
        image.onload = () => {
          const { width, height } = image;
          if (width !== 40 || height !== 40) {
            this.$message.error('请上传40px*40px 的图片！');
            isSize = false;
            this.bgImgs = []  //背景图清空，由于isSize=false 未及时在return时返回，so，需要在分辨率错误后，清空背景图数据
            console.log('isSize', isSize);
          };
        };
      };

      // const isJPG = file.type === 'image/jpeg';
      const isJPG = file.type;
      const isLt2M = file.size / 1024 / 1024 < 2;

      const extension1 = file.type === "image/jpg";
      const extension2 = file.type === "image/jpeg";
      const extension3 = file.type === "image/png";
      if (!extension1 && !extension2 && !extension3) {
        this.$message.error("请上传jpg 、png、jpeg 类型图片!");
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }

      console.log('isJPG && isLt2M && isSize', isJPG && isLt2M && isSize, isJPG, isLt2M, isSize)

      return isJPG && isLt2M && isSize;
    },


    /* 删除增加确认弹窗 */
    onBeforeRemove () {
      return new Promise((resolve, reject) => {
        this.$confirm('确定要删除吗?', '提示', {
          type: 'warning'
        })
          .then(() => {
            console.log("进入图标删除=======")
            this.form.icon = ''
            resolve();
          })
          .catch(() => {
            console.log("进入图标删除取消=======")
            reject();
          });
      });
    },
    sortLabelListFn () {

    },
    /* 更新visible */
    updateVisible (value) {
      if (value == false) {
        this.loading = false;
        //  图片清空
        this.form.icon = ''
        this.bgImgs = []
      }
      this.$emit('update:visible', value);
    }
  },
  watch: {
    visible (visible) {
      console.log("this.data", this.data)
      if (visible) {
        if (this.data) {
          this.bgImgs = []
          this.form = { ...this.data }
          this.isUpdate = true;
          let info = {}
          info.url = this.data.icon
          this.bgImgs.push(info)
          console.log("this.bgImgs", this.bgImgs)
        } else {
          this.isUpdate = false;
        }
      } else {
        this.$refs.form.clearValidate();
        this.form = { ...this.defaultForm };
      }
      console.log("this.form", this.form)

    }
  }
};
</script>
<style lang="less" scoped>
/*隐藏input（type=number)右边的小箭头*/
/deep/ .el-input--medium .el-input__inner {
  line-height: 37px !important;
}
/deep/.delInput input::-webkit-outer-spin-button,
/deep/.delInput input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
}
/deep/.delInput input[type='number'] {
  -moz-appearance: textfield;
}
</style>
